import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/photo_params.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 发布动态视图模型
/// 管理发布动态页面的数据和状态
class PublishPostViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final PostStudio _postStudio;

  PublishPostViewModel(this._authFocus, this._postStudio);

  PostCategory _selectedCategory = PostCategory.dailyLife;
  PostCategory get selectedCategory => _selectedCategory;

  List<String> _selectedImages = [];
  List<String> get selectedImages => _selectedImages;

  String _content = '';
  String get content => _content;

  PhotoParams? _photoParams;
  PhotoParams? get photoParams => _photoParams;

  /// 设置分类
  void setCategory(PostCategory category) {
    _selectedCategory = category;
    notifyListeners();
  }

  /// 设置内容
  void setContent(String value) {
    _content = value;
    notifyListeners();
  }

  /// 设置摄影参数
  void setPhotoParams(PhotoParams params) {
    _photoParams = params;
    notifyListeners();
  }

  /// 选择图片
  Future<void> selectImages(BuildContext context) async {
    try {
      // 计算还可以选择多少张图片
      final remainingSlots = 3 - _selectedImages.length;
      if (remainingSlots <= 0) {
        return; // 已经选择了 3 张图片
      }

      final List<AssetEntity>? selectedAssets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: remainingSlots,
          requestType: RequestType.image,
        ),
      );

      if (selectedAssets == null || selectedAssets.isEmpty) {
        return; // 用户取消了选择
      }

      // 将图片复制到本地目录
      final imagePaths = <String>[];
      for (final asset in selectedAssets) {
        final localPath = await _copyImageToLocal(asset);
        if (localPath != null) {
          imagePaths.add(localPath);
        }
      }

      // 将新选择的图片添加到已选择的图片列表中
      if (imagePaths.isNotEmpty) {
        _selectedImages.addAll(imagePaths);
        // 确保列表长度不超过 3
        if (_selectedImages.length > 3) {
          _selectedImages = _selectedImages.take(3).toList();
        }
        notifyListeners();
      }
    } catch (e) {
      // 错误处理
    }
  }

  /// 将图片复制到本地目录
  Future<String?> _copyImageToLocal(AssetEntity asset) async {
    try {
      // 获取应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      final imagesDir = Directory('${directory.path}/post_images');

      // 如果目录不存在，创建它
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      // 生成唯一的文件名（清理路径分隔符）
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final random = asset.id.toString().replaceAll(RegExp(r'[/\\]'), '_');
      final fileName = 'post_${timestamp}_$random.jpg';
      final filePath = '${imagesDir.path}/$fileName';

      // 读取图片数据
      final file = await asset.file;
      if (file == null) {
        return null;
      }

      // 确保目标文件的父目录存在
      final localFile = File(filePath);
      if (!await localFile.parent.exists()) {
        await localFile.parent.create(recursive: true);
      }

      // 复制文件到本地目录
      await file.copy(localFile.path);

      // 返回本地路径（用于存储和显示）
      return localFile.path;
    } catch (e) {
      return null;
    }
  }

  /// 删除图片
  void removeImage(int index) {
    if (index >= 0 && index < _selectedImages.length) {
      _selectedImages.removeAt(index);
      notifyListeners();
    }
  }

  /// 发布动态
  Future<bool> publishPost() async {
    if (_selectedImages.length != 3) {
      return false;
    }

    if (_content.trim().isEmpty) {
      return false;
    }

    if (_selectedCategory == PostCategory.photography && _photoParams == null) {
      return false;
    }

    final currentUser = await _authFocus.getCurrentUser();
    if (currentUser == null) {
      return false;
    }

    setBusy(true);
    try {
      await _postStudio.publishPost(
        authorId: currentUser.id,
        category: _selectedCategory,
        images: _selectedImages,
        content: _content.trim(),
        photoParams: _photoParams,
      );
      return true;
    } catch (e) {
      return false;
    } finally {
      setBusy(false);
    }
  }
}
